<template>
	<div class="navbar">
		<div class="navbar-left">
			<div class="left-title">{{ userInfo?.deptName }}</div>
			<div class="search">
				<zsearchInput></zsearchInput>
			</div>
		</div>
		<div class="navbar-right">
			<div class="right-btns">
				<el-button :icon="Plus" class="btn-3" v-jurisdiction="'customer:info:add'"  @click="addPatient">新增患者</el-button>
				<el-button class="btn-4 iconfont icon-jinru_huabanfuben" v-jurisdiction="'work:customer:registered'"  @click="clickRegister">挂号</el-button>
			</div>
			<div class="user-info">
				<el-avatar :src="AvatarImg" :size="60" style="background: transparent"></el-avatar>
				<div class="user-name">
					<el-dropdown @command="handleCommand">
						<span class="el-dropdown-link">
							{{ userInfo?.userName }}<el-icon><ArrowDown /></el-icon>
						</span>
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item command="switch">切换账号</el-dropdown-item>
								<el-dropdown-item command="switchBranch">切换分院</el-dropdown-item>
								<el-dropdown-item command="editPwd">修改密码</el-dropdown-item>
								<el-dropdown-item command="LogOut">退出登录</el-dropdown-item>
							</el-dropdown-menu>
						</template>
					</el-dropdown>
				</div>
			</div>
		</div>
	</div>

	<zdialog :width="'55%'" title="新增患者" @handleClose="drawerClose" v-model="showDialog">
		<template #body>
			<zaddpatient
					ref="zaddpatientRef"
					@cancel="cancel" 
					@saveMakeAnAppointment="saveMakeAnAppointment" 
					@saveAndRegister="saveAndRegister"
					v-if="isADD === 'add'"
					></zaddpatient>
		</template>
	</zdialog>

	<!-- 新增/挂号/ 预约/  -->
  <el-drawer
			size="45%"
			:title="title"
			v-model="showDrawer"
			:before-close="drawerClose" destroy-on-close>
				<zaddpatient 
					@cancel="cancel" 
					@saveMakeAnAppointment="saveMakeAnAppointment" 
					@saveAndRegister="saveAndRegister"
					v-if="isADD === 'add'"
					></zaddpatient>
			
				<zregister v-if="isADD === 'register'"
					@cancel="cancel" 
					@handlebtn="handlebtn"
					:userId="personId"
					></zregister>
					

				<zmakeanapp v-if="isADD === 'makeanapp'"
					@handlebtn="handlebtn"
					@cancel="cancel"
					:personName="personName"
					:personId="coustomId"
					></zmakeanapp>
	</el-drawer>


	<!-- 切换分院 -->
	    <zdialog title="切换分院" @handleClose="closeDialog" v-model="dialogVisible" :btnData="dialogBtnData">
      <template #body>
        <div class="leftToRight-layout" style="width: 100%;">
					<!-- <div class="label">
						<span></span>
					</div> -->
					<div class="operations" >
						<el-select v-model="branchList"  placeholder="请选择分院">
							<el-option
								v-for="item in branchOptions"
								:key="item.id"
								:label="item.name"
								:value="item.id">
							</el-option>
						</el-select>
					</div>
				</div>
			</template>
    </zdialog>

		<!-- 修改密码 -->
	  <zdialog title="修改密码" @handleClose="closeEdit" v-model="editPwdShow" :btnData="editBtn">
      <template #body>
        <el-form
					ref="ruleFormRef"
					:model="ruleForm"
					:rules="rules"
					label-width="80px"
					class="demo-ruleForm"
				>
				<el-form-item label="旧密码" prop="oldPassword">
					<el-input v-model="ruleForm.oldPassword" />
				</el-form-item>
				<el-form-item label="新密码" prop="newPassword">
					<el-input v-model="ruleForm.newPassword" />
				</el-form-item>
				</el-form>
			</template>
    </zdialog>

</template>

<script lang="ts">
import { ArrowDown, Plus } from '@element-plus/icons-vue'
import { defineComponent, PropType, ref, toRef, onUnmounted, onMounted, nextTick, reactive } from "vue";
import { User } from "../../hook/user";
import useShowWidget from "../../components/widget/usechoose";
import useRequet, { RespData } from "../../hook/network"
import useConfgin from '../../hook/getconfig'
import ztitleBorder from "../../components/titleBorder/titleBorder.vue"
import zaddpatient from "../../components/patient/add.vue"
import zregister from "../../components/patient/register.vue"
import zmakeanapp from "../../components/patient/makeAnAppointment.vue"
import zdialog from '@components/dialog/dialog.vue'
import zsearchInput from '../../components/searchinput/searchinput.vue'

import useDataCheck from '../../hook/datastruc'
import {Option} from "../../types"

import AvatarImg from "../../assets/image/avatar.png"

import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

import { updateSelfPasswordAPi } from '../../api/common'


import zdrawer from "@components/drawer/drawer.vue";
import router from '../../router';
const ID = 518 // 患者中心
const RELATION = 519 // 患者关系
const INITIALDIAGNOSIS = 520 // 	客户初诊
export default defineComponent({
	name: "NavBar",
	props: {
		userInfo:{
type:Object as PropType<User>,

		} 
	},
	components: {
		zdrawer,
		ztitleBorder,
		zaddpatient,
		zregister,
		zmakeanapp,
		zsearchInput,

		zdialog,

		ArrowDown,
		Plus
	},
	emits:['switchBtn', 'LogOutBtn'],
	setup(props, ctx) {
		const personId = ref(0)
		const personName = ref('')
		const handleCommand = (command: string) => {
			if (command === "switch") {
				console.debug("切换账号");
				switchBtn();
			} else if (command === 'switchBranch') {
				console.log('切换分院')
				dialogVisible.value = true
				getBranchList()
			} else if (command === "LogOut") {
				console.debug("退出登录");
				LogOutBtn();
			} else if (command === "editPwd") {
				console.debug("修改密码");
				editPwd()
			} else {
				return false;
			}
			// ElMessage(`click on item ${command}`);
		};
		const switchBtn = () => {
			ctx.emit("switchBtn");
		};

		const LogOutBtn = () => {
			ctx.emit("LogOutBtn");
		};

		const ruleFormRef = ref<FormInstance>()
		const ruleForm = reactive({
			oldPassword: '',
			newPassword: '',
		})
		const rules = reactive<FormRules>({
			oldPassword: [
				{ required: true, message: '旧密码不能为空', trigger: 'blur' }
			],
			newPassword: [
				{ required: true, message: '密码不能为空', trigger: 'blur' },
			],
		})

		const editPwdShow = ref(false)
		// 打开
		const editPwd = () => {
			editPwdShow.value = true
		}
		// 关闭
		const closeEdit = () => {
			editPwdShow.value = false;
			ruleForm.newPassword = '';
			ruleForm.oldPassword = '';
		}

		// 确定
		const pwdSave = () => {
			(ruleFormRef.value as FormInstance).validate(async(valid, fields) => {
				if (valid) {
					console.log('submit!', ruleForm)
					let res:any = await updateSelfPasswordAPi(ruleForm)
					if(res.code !== 0) return ElMessage.error('修改密码' + res.msg)
					ElMessage.success('修改成功');
					
					closeEdit()

					switchBtn()
				} else {
					console.log('error submit!', fields)
				}
			})
		}

		// 弹窗按钮
		const editBtn = [
			{
        name: '取消',
				func: (data:object) => {
          closeEdit()
				}
      },
			{
        name: '确定',
				func: (data:object) => {
          pwdSave()
				}
      },
		]
		

		const dataCheck = useDataCheck();
		const request = useRequet({ path: "" });
		const {groupData, groupDataAdd, groupDataUpdate} = useConfgin(ID)
		const infoAdd = groupDataAdd
		const resultTotal = useConfgin(RELATION)
		const resultAdd = resultTotal.groupDataAdd
		const InitialDiagnosis = useConfgin(INITIALDIAGNOSIS)
		const DiagnosisAdd = InitialDiagnosis.groupDataAdd

		// 切换分院
		const branchList = ref('')
		const branchOptions = ref([] as Option[])
		const dialogVisible = ref(false)
		
		const closeDialog = () => {
			dialogVisible.value = false
		}
		const dialogBtnData = [
			{
        name: '取消',
				func: (data:object) => {
					console.debug('取消',JSON.parse(JSON.stringify(data)))
          closeDialog()
				}
      },
			{
        name: '确定',
				func: (data:object) => {
					console.debug('确定',JSON.parse(JSON.stringify(data)))
					request.sendRequest({
						address: `sys/index/switchSubCompany/${branchList.value}`,
						params: {},
						success: (resp: RespData) => {
							if(resp.code !== 0) return ElMessage.error(resp.msg)
							closeDialog()
							
							window.localStorage.removeItem('currentPath')
							window.localStorage.removeItem('activeName')
							let url:any = window.localStorage.getItem('firstPath')
							window.localStorage.setItem('currentPath', url)
							if(url) {
								router.push(url)
							}
							setTimeout(() => {
								window.location.reload()
							}, 1000)
							
							
							
						},
						fail: (resp: RespData) => {
							if(resp.code !== 0) return ElMessage.error(resp.msg)
							
						},
						method: "POST",
					})
				}
      },
		]
		const getBranchList = () => {
			request.sendRequest({
        address: 'company/subCompany/getAllSubCompany',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
					branchOptions.value = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
		}
		const zaddpatientRef = ref()
		let showDrawer = ref(false)
		let showDialog = ref(false)
		const showWidget = useShowWidget;
		const drawerClose = () => {
			ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
				showDrawer.value = false
				showDialog.value = false
				personId.value = 0

				zaddpatientRef.value.cancel()
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
		}

		const title = ref('')
		const isADD = ref('')
		const addPatient = () => {
			showDialog.value = true
			title.value = '个人信息'
			isADD.value = 'add'


			zaddpatientRef.value && (zaddpatientRef.value.isRefreshPage = true)
		}

		const cancel = () => {
			showDrawer.value = false
			showDialog.value = false

			personId.value = 0
		}

	

		const saveAndRegister = async(userId: number) => {
			showDialog.value = false
			showDrawer.value = true
			personId.value = userId
			isADD.value = 'register'
			title.value = "挂号"
			console.log(personId.value, userId)
		}

		const coustomId = ref(0)
		const saveMakeAnAppointment = (name: string, userId:number) => {
			showDialog.value = false
			showDrawer.value = true
			personName.value = name
			coustomId.value = userId
			isADD.value = 'makeanapp'
			title.value = "新建预约"
		}

		const handlebtn = () => {
			isADD.value = 'add'
			title.value = "个人信息"
		}

		const clickRegister = () => {
			showDrawer.value = true
			isADD.value = 'register'
			title.value = "挂号"
		}
		type Records = {
			startTime: string,
			primaryCareDoctor: number,
			actionChief: string,
			preliminaryJudgment: string,
			symptoms: string
		}
		const save = () => {
			let result = {
				customerInfo:{
					other: {}
				},
				deptConfig: {},
				records: {} as Records
			} as any
			infoAdd.value.forEach(item => {
				console.log(item.name.split('.'))
				if(item.type === 502 && item.value) {
					item.value = item.value + ' ' + '00:00:00'
				}
				if(item.name.split('.')[0] === 'other') {
					result.customerInfo.other[item.name.split('.')[1]] = item.value
				} else {
					result.customerInfo[item.name]= item.value
				}
			})
			resultAdd.value.forEach(item => {
				if(item.type === 502 && item.value) {
					item.value = item.value + ' ' + '00:00:00'
				}
				result.deptConfig[item.name] = item.value
			})
			DiagnosisAdd.value.forEach(item => {
				if(item.type === 502 && item.value) {
					item.value = item.value + ' ' + '00:00:00'
				}
				result.records[item.name] = item.value
			})

      if(!dataCheck.checkAll()) {
          return false
      }
      request.sendRequest({
        address: 'customer/info/createCustomer',
        params: result,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '保存失败')
          ElMessage.success(resp.msg || '保存成功')
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '保存失败')
          
        },
        method: "POST",
      })
			
		}

		onUnmounted(() => {
			dataCheck.clearDataCheck();
		});
		return {
			AvatarImg,
			handleCommand,
			switchBtn,
			LogOutBtn,
			title,
			personId,
			personName,
			coustomId,

			branchList,
			branchOptions,
			dialogVisible,
			closeDialog,
			dialogBtnData,

			zaddpatientRef,

			editPwdShow,
			closeEdit,
			editBtn,
			ruleFormRef,
			ruleForm,
			rules,

			addPatient,
			showDrawer,
			showDialog,
			showWidget,
			drawerClose,
			cancel,
			save,
			saveAndRegister,
			saveMakeAnAppointment,
			handlebtn,
			isADD,
			clickRegister,

			groupData,
			infoAdd,
			resultAdd,
			DiagnosisAdd,
			groupDataAdd,


			request,
			Plus
		};
	},
});
</script>

<style lang="scss" scoped>
.navbar {
	height: 100%;
	display: flex;
	.navbar-left {
		flex: 2;
		display: flex;
		align-items: center;
		.left-title {
			padding: 0 30px;
			font-size: $fontSize-3;
			font-weight: 600;
			color: $primaryText;
		}
	}
	.navbar-right {
		/* flex: 1; */
		display: flex;
		align-items: center;

		.user-info {
			display: flex;
			align-items: center;
			padding-left: 20px;
			margin-right: 50px;
			> span {
				width: 42px;
				height: 42px;
				line-height: 42px;
			}
			.user-name {
				padding-left: 10px;
			}
		}
	}
}

</style>
